// mapUtils 地图工具类，封装了 Bigemap 地图的初始化、绘制、编辑、吸附等功能
class mapUtils {
    // 构造函数，初始化地图工具类
    constructor(mapContainerId, mapType, options = {}, onMapEvent) {
        this.mapContainerId = mapContainerId; // 地图容器的 DOM id
        this.map = null; // 地图实例对象
        this.mapType = mapType; // 地图类型（如 bigemap.2i5fd1il）
        this.options = options; // 地图初始化配置项
        this.draw = null; // 绘图对象（用于绘制点、线、面等）
        this.edit = null; // 编辑对象（用于编辑已绘制的图形）
        this.adsorb = null; // 吸附对象（用于图形吸附功能）
        this.arr = []; // 点线面的经纬度坐标
        this.type = null; // 点击的类型  // 点：marker | 线：polyline | 面：polygon
        this.onMapEvent = onMapEvent; // 新增：事件回调
        this.drawnLayers = []; // 记录所有绘制的图层
        this.measurePlugin = null; // 记录测距控件实例
        // 在 mapUtils 类中添加属性
        this.measurePolygon = null;
        this.measureDeleteMarker = null;
        this.fillColor = options.fillColor || '#ff000088'; // 默认填充色
    }

    // 初始化地图，加载 Bigemap 并设置中心、缩放、边界等
    initMap() {
        console.log('开始初始化地图，容器ID:', this.mapContainerId);
        console.log('容器元素:', document.getElementById(this.mapContainerId));
        
        // 检查 Bigemap API 是否已加载
        if (typeof BM === 'undefined') {
            throw new Error('Bigemap API 未加载'); // Bigemap 未加载时报错
        }
        // 设置地图服务地址
        BM.Config.HTTP_URL = this.options.httpUrl || 'http://192.168.110.210:3000';
        // 设置地图访问令牌
        BM.accessToken = this.options.accessToken || '';
        // 确定地图类型
        const finalMapType = this.mapType || this.options.mapType || 'bigemap.2i5fd1il';
        // 创建地图实例，挂载到指定容器
        console.log('创建地图实例，类型:', finalMapType, '配置:', {
            center: this.options.center,
            zoom: this.options.zoom || 18
        });
        
        this.map = BM.map(this.mapContainerId, finalMapType, {
            center: this.options.center, // 地图中心点坐标
            zoom: this.options.zoom || 18, // 默认缩放级别
            zoomControl: false, // 显示缩放控件
            doubleClickZoom: false, // 禁止双击放大
        });
        
        console.log('地图实例创建成功:', this.map);
        // 如果有设置显示边界，则应用边界
        if (this.options.fitBounds) {
            this.map.fitBounds(this.options.fitBounds); // 设置显示边界
        }
        // 点击地图事件，回调传递经纬度
        this.map.on('click', (e) => {
            if (e && e.latlng && this.onMapEvent) {
                this.onMapEvent({ type: 'click', coords: e.latlng });
            }
        });
    // 初始化绘图、编辑、吸附对象（如果相关脚本已加载）
    if (typeof BM.Plot !== 'undefined') {
        this.initPlotDraw();
        this.initPlotEdit();
        this.initPlotAdsorbManager();
    } else {
        console.warn('BM.Plot 未加载，跳过绘图功能初始化');
    }
        this.addMarker();
    }

    // 鼠标左键点击地图添加 marker 点
    addMarker() {
        // 先移除之前的点击事件，避免重复绑定
        if (this._markerClickHandler) {
            this.map.off('click', this._markerClickHandler);
        }
        
        // 绑定地图点击事件，每次点击在点击处添加一个 marker
        this._markerClickHandler = function (e) {
            // BM.marker(e.latlng).addTo(this); // 在点击位置添加 marker
        };
        
        this.map.on('click', this._markerClickHandler);
    }

    // 启用点击添加marker功能
    enableClickToAddMarker() {
        // 先禁用绘图工具
        if (this.draw && typeof this.draw.disable === 'function') {
            this.draw.disable();
        }
        
        // 先移除之前的点击事件，避免重复绑定
        if (this._clickToAddMarkerHandler) {
            this.map.off('click', this._clickToAddMarkerHandler);
        }
        
        // 绑定地图点击事件，每次点击在点击处添加一个 marker
        this._clickToAddMarkerHandler = (e) => {
            if (e && e.latlng) {
                this.addMarkerAtPosition(e.latlng.lat, e.latlng.lng, {
                    title: '点击添加的标记',
                    draggable: true
                });
            }
        };
        
        this.map.on('click', this._clickToAddMarkerHandler);
    }

    // 禁用点击添加marker功能
    disableClickToAddMarker() {
        if (this._clickToAddMarkerHandler) {
            this.map.off('click', this._clickToAddMarkerHandler);
            this._clickToAddMarkerHandler = null;
        }
    }

    // 在指定位置添加 marker
    addMarkerAtPosition(lat, lng, options = {}) {
        if (!this.map) {
            console.error('地图实例不存在');
            return null;
        }
        
        const marker = BM.marker([lat, lng], options).addTo(this.map);
        
        // 添加到管理列表
        this.drawnLayers.push(marker);
        
        // 添加删除按钮
        this.addDeleteButton(marker, [lat, lng]);
        
        return marker;
    }

    // 批量添加 markers
    addMarkers(markersData) {
        if (!Array.isArray(markersData)) {
            console.error('markersData 必须是数组');
            return [];
        }
        
        const markers = [];
        markersData.forEach(data => {
            if (data.lat && data.lng) {
                const marker = this.addMarkerAtPosition(data.lat, data.lng, data.options || {});
                if (marker) {
                    markers.push(marker);
                }
            }
        });
        
        return markers;
    }

    // 添加带自定义图标的 marker
    addCustomMarker(lat, lng, iconUrl, options = {}) {
        if (!this.map) {
            console.error('地图实例不存在');
            return null;
        }
        
        console.log('尝试添加自定义图标marker:', { lat, lng, iconUrl, options });
        
        // 检查图片是否存在
        const img = new Image();
        img.onload = () => {
            console.log('图片加载成功:', iconUrl);
        };
        img.onerror = () => {
            console.error('图片加载失败:', iconUrl);
        };
        img.src = iconUrl;
        
        try {
            const customIcon = BM.icon({
                iconUrl: iconUrl,
                iconSize: options.iconSize || [32, 32],
                iconAnchor: options.iconAnchor || [16, 16],
                popupAnchor: options.popupAnchor || [0, -16]
            });
            
            console.log('创建的自定义图标:', customIcon);
            
            const marker = BM.marker([lat, lng], {
                icon: customIcon,
                ...options
            }).addTo(this.map);
            
            console.log('marker创建成功:', marker);
            
            // 添加到管理列表
            this.drawnLayers.push(marker);
            
            // 添加删除按钮
            this.addDeleteButton(marker, [lat, lng]);
            
            return marker;
        } catch (error) {
            console.error('创建自定义图标marker时出错:', error);
            // 如果自定义图标失败，回退到默认marker
            console.log('回退到默认marker');
            return this.addMarkerAtPosition(lat, lng, options);
        }
    }

    // 添加带弹窗的 marker
    addMarkerWithPopup(lat, lng, popupContent, options = {}) {
        const marker = this.addMarkerAtPosition(lat, lng, options);
        
        if (marker && popupContent) {
            marker.bindPopup(popupContent);
        }
        
        return marker;
    }

    // 添加删除按钮的辅助方法
    addDeleteButton(layer, position) {
        if (!this.map) return;
        
        // 计算删除按钮的位置（在原始位置的右上角）
        const offset = 0.0001; // 经纬度偏移量，让删除按钮显示在右上角
        const deletePosition = [position[0] + offset, position[1] + offset];
        
        const deleteMarker = BM.marker(deletePosition, {
            icon: BM.divIcon({
                className: 'delete-graphic-btn',
                html: '<span style="display:inline-block;width:20px;height:20px;background:#fff;border-radius:50%;box-shadow:0 1px 4px #aaa;line-height:20px;text-align:center;color:#f56c6c;font-size:14px;cursor:pointer;border:1px solid #ddd;">×</span>',
                iconSize: [20, 20],
                iconAnchor: [10, 10],
            }),
            interactive: true,
        }).addTo(this.map);
        
        deleteMarker.on('click', () => {
            this.map.removeLayer(layer);
            this.map.removeLayer(deleteMarker);
            // 从 drawnLayers 移除
            const idx = this.drawnLayers.indexOf(layer);
            if (idx !== -1) this.drawnLayers.splice(idx, 1);
        });
        
        // 让图层和删除按钮绑定，方便后续管理
        layer._deleteMarker = deleteMarker;
    }

    // 初始化鼠标绘制的对象（如点、线、面等）
    // options 可自定义颜色、线宽、填充色
    initPlotDraw(options = { color: 'pink', weight: 2, fillColor: 'red' }) {
        if (typeof BM.Plot === 'undefined') {
            console.warn('BM.Plot 未加载，无法初始化绘图功能');
            return;
        }
        this.draw = new BM.Plot.Draw(this.map, {
            repeat: !0, // 是否允许重复绘制
            doubleArrow: { color: options.color }, // 双箭头样式
            polyline: { weight: options.weight }, // 线的样式（线宽）
            polygon: {
                fillColor: options.fillColor, // 面的填充色
            },
        });

        // 监听绘制结束，回调传递经纬度
        if (this.draw && this.draw.on) {
            this.draw.on('bm_draw_end', (e) => {
                var layer = e.detail.layer;
                var type = e.detail.type;
                var coords = null;
                // 记录每次绘制的图层
                if (layer) {
                  this.drawnLayers.push(layer);
                  // 添加删除按钮
                  let map = this.map;
                  let deleteMarker = null;
                  let pos = null;
                  if (type === 'marker') {
                    pos = layer.getLatLng();
                  } else if (type === 'polyline') {
                    let latlngs = layer.getLatLngs();
                    pos = latlngs[Math.floor(latlngs.length / 2)];
                  } else if (type === 'polygon') {
                    let latlngs = layer.getLatLngs();
                    if (Array.isArray(latlngs[0])) latlngs = latlngs[0];
                    pos = latlngs[Math.floor(latlngs.length / 2)];
                    // 新增：设置当前填充色
                    if (layer.setStyle) {
                      layer.setStyle({ fillColor: this.fillColor });
                    }
                    // 记录自定义颜色
                    layer._customFillColor = this.fillColor;
                  } else if (type === 'circle') {
                    pos = layer.getLatLng && layer.getLatLng();
                    // 新增：设置当前填充色
                    if (layer.setStyle) {
                      layer.setStyle({ fillColor: this.fillColor });
                    }
                    // 记录自定义颜色
                    layer._customFillColor = this.fillColor;
                  } else if (type === 'rectangle') {
                    if (layer.getBounds && typeof layer.getBounds === 'function') {
                      const bounds = layer.getBounds();
                      pos = bounds.getCenter ? bounds.getCenter() : null;
                    }
                    // 新增：设置当前填充色
                    if (layer.setStyle) {
                      layer.setStyle({ fillColor: this.fillColor });
                    }
                    // 记录自定义颜色
                    layer._customFillColor = this.fillColor;
                  }
                  if (pos) {
                    deleteMarker = BM.marker(pos, {
                      icon: BM.divIcon({
                        className: 'delete-graphic-btn',
                        html: '<span style="display:inline-block;width:22px;height:22px;background:#fff;border-radius:50%;box-shadow:0 1px 4px #aaa;line-height:22px;text-align:center;color:#f56c6c;font-size:16px;cursor:pointer;">×</span>',
                        iconSize: [22, 22],
                        iconAnchor: [11, 11],
                      }),
                      interactive: true,
                    }).addTo(map);
                    deleteMarker.on('click', () => {
                      map.removeLayer(layer);
                      map.removeLayer(deleteMarker);
                      // 从 drawnLayers 移除
                      const idx = this.drawnLayers.indexOf(layer);
                      if (idx !== -1) this.drawnLayers.splice(idx, 1);
                    });
                  }
                  // 让图层和删除按钮绑定，方便后续管理
                  layer._deleteMarker = deleteMarker;
                }
                if (type === 'marker') {
                    coords = layer.getLatLng();
                } else if (type === 'polyline' || type === 'polygon') {
                    coords = layer.getLatLngs();
                }
                // 测面积逻辑：只在已绘制的 polygon 上绑定 tooltip，不再新建 polygon
                if (this.activeTool === 'measureArea' && type === 'polygon') {
                  let latLngs = coords;
                  if (Array.isArray(latLngs[0])) latLngs = latLngs[0];
                  if (latLngs && latLngs.length > 2 && typeof this.CalculatePolygonArea === 'function') {
                    const area = this.CalculatePolygonArea(latLngs);
                    let areaStr = area > 1000000 ? (area/1000000).toFixed(2) + ' 平方公里' : area.toFixed(2) + ' 平方米';
                    layer.bindTooltip('面积:' + areaStr).openTooltip();
                  }
                  this.activeTool = null; // 退出测面积模式
                }
                if (this.onMapEvent) {
                    this.onMapEvent({ type: 'draw', drawType: type, coords });
                }
            });
        }
    }

    // 初始化编辑对象，用于编辑已绘制的图形
    initPlotEdit() {
        if (typeof BM.Plot === 'undefined') {
            console.warn('BM.Plot 未加载，无法初始化编辑功能');
            return;
        }
        this.edit = new BM.Plot.Edit(this.map, {
            control: {
                dragging: false, // 编辑时是否允许拖动图形
                vertex: {
                    autoRemove: true, // 顶点是否自动移除
                    withIn: 10, // 顶点可操作范围
                    icon: BM.icon({
                        iconUrl: "/offline_data/newjunbiao/plus.png", // 顶点图标
                        iconSize: [16, 16],
                        iconAnchor: [8, 8],
                    }),
                },
                boundsMarker: {
                    icon: BM.icon({
                        iconUrl: "/offline_data/newjunbiao/dot.png", // 边界点图标
                        iconSize: [16, 16],
                        iconAnchor: [8, 8],
                    }),
                },
                marker: {
                    icon: BM.icon({
                        iconUrl: "/offline_data/newjunbiao/dot.png", // marker 图标
                        iconSize: [8, 8],
                        iconAnchor: [4, 4],
                    }),
                },
            },
        });
    }

    // 设置吸附对象，实现图形吸附功能
    initPlotAdsorbManager() {
        if (typeof BM.Plot === 'undefined') {
            console.warn('BM.Plot 未加载，无法初始化吸附功能');
            return;
        }
        // 创建一个吸附对象，传入地图实例
        this.adsorb = new BM.Plot.AdsorbManager(this.map);
        // 修改吸附距离，单位像素，越大越容易吸附
        this.adsorb.distance = 10;
        // 向吸附对象里添加点、线、面图层（可选）
        // this.adsorb.addLayer(pp);

        // 给绘图对象设置吸附管理对象，实现绘制时吸附
        this.draw.setAdsorbManager(this.adsorb);

        // 给编辑对象设置吸附管理对象，实现编辑时吸附
        this.edit.setAdsorbManager(this.adsorb);
    }

    // 新增：设置当前激活的工具类型
    setActiveTool(tool) {
        this.activeTool = tool;
    }

    // 激活绘制功能，参数 e 为绘制类型（如 marker、polyline、polygon 等）
    initActivate(e) {
        // 同步设置当前激活工具类型
        this.activeTool = e;
        
        // 如果当前处于编辑状态，先禁用编辑，再启用绘制
        if (this.edit && typeof this.edit.isEdit === 'function' && this.edit.isEdit()) {
            this.edit.disable();
        }
        
        // 检查 draw 对象是否存在且有效
        if (!this.draw) {
            console.error('draw 对象不存在，无法启用绘制');
            return;
        }
        
        if (typeof this.draw.enable !== 'function') {
            console.error('draw.enable 方法不存在');
            return;
        }
        
        // 检查地图对象是否有效
        if (!this.map) {
            console.error('map 对象不存在，无法启用绘制');
            return;
        }
        
        try {
            // 确保测距功能完全禁用
            if (this.measurePlugin) {
                this.clearMeasureOnly();
            }
            
        this.draw.enable(e); // 启用指定类型的绘制
        } catch (error) {
            console.error('启用绘制功能时出错:', error);
        }
        
        // 延迟执行 addMarker，避免与绘制功能冲突
        setTimeout(() => {
            try {
                this.addMarker();
            } catch (error) {
                console.error('addMarker 执行出错:', error);
            }
        }, 100);
    }

    addRanging(options = {lineColor: 'red', lineWeight: 2, lineDashArray: '6, 6', lineOpacity: 1}) {
        // 1. 先彻底清理所有测距相关内容
        this.clearMeasureOnly();
        
        // 2. 关闭绘图和编辑控件，确保测距和绘图互斥
        if (this.draw && typeof this.draw.disable === 'function') {
            this.draw.disable();
        }
        if (this.edit && typeof this.edit.disable === 'function') {
            this.edit.disable();
        }
        
        // 3. 检查地图是否有效
        if (!this.map) {
            console.error('地图实例不存在，无法启用测距');
            return;
        }
        
        // 4. 启用测距控件
        try {
        var plugin = BM.control.measure({
            position: 'topleft',
            keyboard: true,
            activeKeyCode: 'M'.charCodeAt(0),
            cancelKeyCode: 27,
            lineColor: 'red',
            lineWeight: 2,
            lineDashArray: '6, 6',
            lineOpacity: 1,
            container: this.map,
            once: true,
            });
            
            // 先清理地图，再添加控件
            plugin.clearMap();
            plugin.addTo(this.map);
        plugin._startMeasuring();
            
            // 记录测距控件实例
            this.measurePlugin = plugin;
            
            // 5. 绑定事件
        this.map.on('start_measure', function (e) {
            console.log('start');
        });
        this.map.on('stop_measure', function (e) {
            console.log('stop', e._layer);
        });
        this.map.on('finish_measure', function (e) {
            console.log('finish', e._layer);
        });
        } catch (error) {
            console.error('创建测距控件时出错:', error);
        }
    }

    getCoordsAndType() {
        return {
            coords: this.coords,
            type: this.type 
        };
    }

    // 专门清理测距相关内容的方法
    clearMeasureOnly() {
        // 1. 清理测距控件
        if (this.measurePlugin) {
            try {
                // 先停止测量
                if (typeof this.measurePlugin._stopMeasuring === 'function') {
                    this.measurePlugin._stopMeasuring();
                }
                if (typeof this.measurePlugin.clear === 'function') {
                    this.measurePlugin.clear();
                }
                if (typeof this.measurePlugin.clearMap === 'function') {
                    this.measurePlugin.clearMap();
                }
                if (typeof this.measurePlugin.destroy === 'function') {
                    this.measurePlugin.destroy();
                }
                if (typeof this.measurePlugin.remove === 'function') {
                    this.measurePlugin.remove();
                }
            } catch (e) {
                console.warn('清理测距控件时出错:', e);
            }
            this.measurePlugin = null;
        }
        
        // 2. 清理测距相关的图层
        if (this.map && typeof this.map.eachLayer === 'function') {
            const layersToRemove = [];
            this.map.eachLayer(layer => {
                if (layer && typeof layer.remove === 'function' && !layer._url) {
                    // 清理测距相关的图层
                    let shouldRemove = false;
                    
                    // 检查类名
                    if (layer.options && layer.options.className && layer.options.className.includes('measure')) {
                        shouldRemove = true;
                    }
                    if (layer._icon && layer._icon.className && layer._icon.className.includes('measure')) {
                        shouldRemove = true;
                    }
                    
                    // 检查测距线条（红色虚线）
                    if (layer instanceof window.BM.Polyline && layer.options && 
                        layer.options.color === 'red' && layer.options.dashArray === '6, 6') {
                        shouldRemove = true;
                    }
                    
                    // 检查测距标记（关闭按钮等）
                    if (layer instanceof window.BM.Marker && layer._icon && layer._icon.className && 
                        (layer._icon.className.includes('close') || 
                         layer._icon.className.includes('bigemap-remove-current-data') ||
                         layer._icon.className.includes('measure'))) {
                        shouldRemove = true;
                    }
                    
                    // 检查其他可能的测距相关属性
                    if (layer._measure || layer._isMeasure || layer._measureLayer) {
                        shouldRemove = true;
                    }
                    
                    if (shouldRemove) {
                        layersToRemove.push(layer);
                    }
                }
            });
            
            // 批量移除图层
            layersToRemove.forEach(layer => {
                try {
                    this.map.removeLayer(layer);
                } catch (e) {
                    console.warn('移除测距图层时出错:', e);
                }
            });
        }
        
        // 3. 清理可能的事件监听器
        if (this.map) {
            try {
                this.map.off('start_measure');
                this.map.off('stop_measure');
                this.map.off('finish_measure');
            } catch (e) {
                console.warn('清理测距事件时出错:', e);
            }
        }
        
        // 4. 确保测距功能完全禁用
        if (this.map && this.map._measureControl) {
            try {
                this.map._measureControl.remove();
                this.map._measureControl = null;
            } catch (e) {
                console.warn('清理测距控制时出错:', e);
            }
        }
    }

    // 清除地图上所有绘制内容（包括测面积、测距、drawnLayers，兜底移除所有测距相关内容和“×”按钮）
    clearAll() {
        // 1. 清除自己管理的内容
        if (this.drawnLayers && this.drawnLayers.length > 0) {
            this.drawnLayers.forEach(layer => {
                if (layer && this.map && typeof this.map.removeLayer === 'function') {
                    this.map.removeLayer(layer);
                    if (layer._deleteMarker) {
                        this.map.removeLayer(layer._deleteMarker);
                    }
                }
            });
            this.drawnLayers = [];
        }
        if (this._measurePolygon) {
            this.map.removeLayer(this._measurePolygon);
            this._measurePolygon = null;
        }
        if (this._measureDeleteMarker) {
            this.map.removeLayer(this._measureDeleteMarker);
            this._measureDeleteMarker = null;
        }
        if (this.measurePlugin) {
            if (typeof this.measurePlugin.clear === 'function') {
                this.measurePlugin.clear();
            }
            if (typeof this.measurePlugin.clearMap === 'function') {
                this.measurePlugin.clearMap();
            }
            if (typeof this.measurePlugin.destroy === 'function') {
                this.measurePlugin.destroy();
            }
            if (this.measurePlugin._layerPaint && typeof this.measurePlugin._layerPaint.clearLayers === 'function') {
                this.measurePlugin._layerPaint.clearLayers();
            }
            if (typeof this.measurePlugin.remove === 'function') {
                this.measurePlugin.remove();
            }
            this.measurePlugin = null;
        }
        // 2. 兜底：移除所有 className 或类型带有 measure/delete/close/bigemap-remove-current-data 的图层（包括marker的icon className）
        if (this.map && typeof this.map.eachLayer === 'function') {
            this.map.eachLayer(layer => {
                if (
                    layer &&
                    typeof layer.remove === 'function' &&
                    (
                        (layer.options && layer.options.className && (
                            layer.options.className.includes('measure') ||
                            layer.options.className.includes('delete') ||
                            layer.options.className.includes('close') ||
                            layer.options.className.includes('bigemap-remove-current-data')
                        ))
                        || (layer._icon && layer._icon.className && (
                            layer._icon.className.includes('measure') ||
                            layer._icon.className.includes('delete') ||
                            layer._icon.className.includes('close') ||
                            layer._icon.className.includes('bigemap-remove-current-data')
                        ))
                        || (layer._path && layer._path.className && layer._path.className.baseVal && (
                            layer._path.className.baseVal.includes('measure') ||
                            layer._path.className.baseVal.includes('delete') ||
                            layer._path.className.baseVal.includes('close') ||
                            layer._path.className.baseVal.includes('bigemap-remove-current-data')
                        ))
                        || (layer instanceof window.BM.Polyline && layer.options && layer.options.color === 'red')
                        || (layer instanceof window.BM.Marker && (
                            (layer._icon && layer._icon.className && layer._icon.className.includes('close'))
                            || (layer._icon && layer._icon.className && layer._icon.className.includes('bigemap-remove-current-data'))
                            || (layer.options && layer.options.icon && layer.options.icon.options && layer.options.icon.options.className && (
                                layer.options.icon.options.className.includes('close') ||
                                layer.options.icon.options.className.includes('bigemap-remove-current-data')
                            ))
                        ))
                    )
                ) {
                    this.map.removeLayer(layer);
                }
            });
        }
    }

    // 切换地图类型（底图）
    switchMapType(type) {
        if (!type) return;
        // 记录当前中心和缩放
        let center = this.map && this.map.getCenter ? this.map.getCenter() : (this.options.center || [28.233838, 112.999839]);
        let zoom = this.map && this.map.getZoom ? this.map.getZoom() : (this.options.zoom || 18);
        // 彻底清理所有工具和图层
        this.clearAll();
        // 移除原有地图实例
        if (this.map && this.map.remove) {
            this.map.remove();
        }
        // 不再移除比例尺控件
        // 不再清空 mapContainer.innerHTML，避免破坏 Vue 工具栏
        // 更新 mapType
        this.mapType = type;
        // 重新初始化地图
        this.map = BM.map(this.mapContainerId, type, {
            center: center,
            zoom: zoom,
            zoomControl: false,
            doubleClickZoom: false,
        });
        // 重新初始化所有工具
        this.initPlotDraw();
        this.initPlotEdit();
        this.initPlotAdsorbManager();
        this.addMarker();
        // 重新绑定事件
        this.map.on('click', (e) => {
            if (e && e.latlng && this.onMapEvent) {
                this.onMapEvent({ type: 'click', coords: e.latlng });
            }
        });
    }

    // 新增：添加多边形并管理到 drawnLayers
    addPolygon(latlngs, options = {}) {
        if (this.map && window.BM && typeof BM.polygon === 'function') {
            const polygon = BM.polygon(latlngs, options).addTo(this.map);
            this.drawnLayers.push(polygon);
            return polygon;
        }
        return null;
    }

    // 测面
    CalculatePolygonArea(latLngs) {
        var pointsCount = latLngs.length,
            area = 0.0,
            d2r = Math.PI / 180,
            p1, p2;

        if (pointsCount > 2) {
            for (var i = 0; i < pointsCount; i++) {
                p1 = latLngs[i];
                p2 = latLngs[(i + 1) % pointsCount];
                area += ((p2.lng - p1.lng) * d2r) *
                    (2 + Math.sin(p1.lat * d2r) + Math.sin(p2.lat * d2r));
            }
            area = area * 6378137.0 * 6378137.0 / 2.0;
        }

        return Math.abs(area);
    }

    // 面积弹层弹层
    openTooltip(latlngs, color = 'red', area) {
        let map = this.map;

        // 先清理上一次的测面积 polygon 和 deleteMarker
        if (this.measurePolygon) {
            map.removeLayer(this.measurePolygon);
            this.measurePolygon = null;
        }
        if (this.measureDeleteMarker) {
            map.removeLayer(this.measureDeleteMarker);
            this.measureDeleteMarker = null;
        }

        var polygon = BM.polygon(latlngs, { color: color }).addTo(map);
        polygon.bindTooltip('面积:' + area + '㎡').openTooltip();

        let pos = latlngs[Math.floor(latlngs.length / 2)];
        let deleteMarker = BM.marker(pos, {
            icon: BM.divIcon({
                className: 'delete-graphic-btn',
                html: '<span style="display:inline-block;width:22px;height:22px;background:#fff;border-radius:50%;box-shadow:0 1px 4px #aaa;line-height:22px;text-align:center;color:#f56c6c;font-size:16px;cursor:pointer;">×</span>',
                iconSize: [22, 22],
                iconAnchor: [11, 11],
            }),
            interactive: true,
        }).addTo(map);

        deleteMarker.on('click', () => {
            map.removeLayer(polygon);
            map.removeLayer(deleteMarker);
            this.measurePolygon = null;
            this.measureDeleteMarker = null;
        });

        polygon._deleteMarker = deleteMarker;

        // 记录当前测面积 polygon 和 deleteMarker
        this.measurePolygon = polygon;
        this.measureDeleteMarker = deleteMarker;
    }

    // 禁用绘制和编辑功能
    disableDraw() {
        if (this.draw && typeof this.draw.disable === 'function') {
            this.draw.disable();
        }
        if (this.edit && typeof this.edit.disable === 'function') {
            this.edit.disable();
        }
    }

    // 设置绘制颜色
    setDrawColor(options) {
        if (options && options.fillColor) {
            this.fillColor = options.fillColor;
        }
    }
}

// 导出 mapUtils 类，供外部使用
export default mapUtils;